﻿# -*-coding:utf-8-*-
import os
import re
from Logs.log import log1
from crawl.best_seller.Basic_class import BestSelling
from crawl.best_seller.seller_urls import bestbuy_urls


class BestBuyBestSelling(BestSelling):
    def __init__(self, url, customerNo):
        super(BestBuyBestSelling, self).__init__()
        self.url = url
        self.headers = {'User-Agent': "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"}
        self.url_main = "https://www.bestbuy.com"
        self.ECOMMERCE_CODE = "100"  # 网站代码
        self.customerNo = customerNo
        self.BASE_DIR = os.path.dirname(os.path.abspath(__file__))

    def product_list(self, html):
        # 获取前10产品信息(SKU_ID,ECOMMERCE_CODE,INSIDE_TYPE,排名,链接,标题,图片)
        # 主标签
        lis = html.xpath("//ol[@class='sku-item-list']/li[@class='sku-item']")
        for li in lis[0:10]:
            try:
                # 链接
                href = self.url_main + li.xpath(".//a[@class='image-link']/@href")[0]
                # try:
                #     href = self.url_main + li.xpath(".//a[@class='image-link']/@href")[0]
                # except:
                #     href = self.url_main + li.xpath(".//div[@class='sku-title']/h4/a/@href")[0]
                # SKU_ID = re.search(r"skuId=(\d+)", href).group(1)
                # 排名
                sort_by = "#%02d" % (lis.index(li) + 1)
                # 标题 product-image
                title = li.xpath(".//div[@class='sku-title']/h4/a/text()")[0].replace("'", "")
                # 图片
                img_url = li.xpath(".//img/@src")[0]
                SKU_ID = re.search(r"/(\d+)_sd.jpg", img_url).group(1)
            except:
                continue
            # 保存图片
            path_img = "img/{}.jpg".format(SKU_ID)
            path_img = os.path.join(self.BASE_DIR, path_img)
            html_img = self.parse_img_url(img_url)
            with open(path_img, 'wb') as file:
                file.write(html_img)
            data = {'type':'new','prodID':'','customerNo':self.customerNo,'customerType':self.INSIDE_TYPE,'prodCode':sort_by,'prodName':title[:300],'prodDesc':title,'prodStatus':self.skuStatus,'fileName':'','GUID':''}
            prodID = self.eip_add(data, path_img)
            self.product_add(SKU_ID, prodID, href)

    def run(self):
        try:
            # self.clean_img()
            self.update_review()
            self.delete_sku_detail()
            self.clean_sku_master()
            html = self.parse_url()
            self.product_list(html)
        except Exception as e:
            log1.error("{}更新失败:{}".format(self.customerNo, e), exc_info=1)
            return
        log1.info("{}更新成功".format(self.customerNo))



if __name__ == '__main__':
    list_bestbuy = bestbuy_urls()
    for tuple2 in list_bestbuy:
        BestBuyBestSelling(*tuple2).run()